<template>
    <div class="my-achievements-container">
        <div class="filter-container">
            <el-form :inline="true" :model="listQuery" class="demo-form-inline">
                <el-form-item label="成果类型">
                    <el-select v-model="listQuery.achievementType" placeholder="请选择成果类型" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="论文" :value="1" />
                        <el-option label="专利" :value="2" />
                        <el-option label="竞赛证书" :value="3" />
                        <el-option label="项目计划" :value="4" />
                        <el-option label="其他" :value="5" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-select v-model="listQuery.status" placeholder="请选择审核状态" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="待初审" :value="0" />
                        <el-option label="初审通过" :value="1" />
                        <el-option label="初审拒绝" :value="2" />
                        <el-option label="终审通过" :value="3" />
                        <el-option label="终审拒绝" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="级别">
                    <el-select v-model="listQuery.level" placeholder="请选择级别" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="国家级" :value="1" />
                        <el-option label="省级" :value="2" />
                        <el-option label="市级" :value="3" />
                        <el-option label="校级" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="成果标题">
                    <el-input v-model="listQuery.title" placeholder="请输入成果标题" style="width: 200px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleFilter">
                        搜索
                    </el-button>
                    <el-button icon="el-icon-refresh" @click="handleReset">
                        重置
                    </el-button>
                    <el-button type="success" icon="el-icon-plus" @click="handleAdd">
                        申报成果
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
            style="width: 100%">
            <el-table-column align="center" label="ID" width="80">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="成果标题" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span class="title-text">{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="成果类型" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.achievementType)">
                        {{ getTypeLabel(scope.row.achievementType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="级别" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.level" size="small" :type="getLevelTagType(scope.row.level)">
                        {{ getLevelLabel(scope.row.level) }}
                    </el-tag>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="绑定课程" width="150" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.course">{{ scope.row.course }}</span>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="学期" width="120" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.semester">{{ scope.row.semester }}</span>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="指导教师" width="120" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.teacherName">{{ scope.row.teacherName }}</span>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="审核状态" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="提交时间" width="160" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="附件" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-dropdown v-if="scope.row.attachments && scope.row.attachments.length > 0" trigger="click">
                        <el-button type="text" size="small" class="attachment-btn">
                            附件下载 <i class="el-icon-arrow-down el-icon--right" />
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                class="attachment-item" @click.native="handleDownloadAttachment(file)">
                                <i :class="getFileIcon(file.fileType)" class="file-icon" />
                                <span class="file-name">{{ file.name }}</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleView(scope.row)">
                        查看
                    </el-button>
                    <el-button v-if="canEdit(scope.row)" type="warning" size="mini" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button v-if="canDelete(scope.row)" type="danger" size="mini" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
            @pagination="getList" />
    </div>
</template>

<script>
import { getMyAchievements, deleteAchievement } from '@/api/achievement'
import Pagination from '@/components/Pagination'

export default {
    name: 'MyAchievements',
    components: { Pagination },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                level: '',
                title: ''
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            this.listLoading = true;
            try {
                const res = await getMyAchievements(this.listQuery)
                this.list = res.data.records || [];
                this.total = res.data.total || 0;
                this.list.forEach(item => {
                    // 解析附件URL
                    if (item.fileUrl) {
                        try {
                            item.attachments = JSON.parse(item.fileUrl)
                        } catch (e) {
                            item.attachments = []
                        }
                    } else {
                        item.attachments = []
                    }
                })
            } catch (error) {
                console.error('获取成果列表失败:', error)
            } finally {
                this.listLoading = false;
            }
            // 模拟数据
            /* setTimeout(() => {
                const mockData = {
                    records: [
                        {
                            id: 1,
                            title: '基于深度学习的图像识别算法研究',
                            achievementType: 1,
                            level: 1,
                            course: '人工智能导论',
                            semester: '2024-2025-1',
                            status: 3,
                            teacherId: 1,
                            teacherName: 'zhangzihan',
                            createTime: '2024-10-15 14:30:00',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '论文全文.pdf',
                                    url: 'https://example.com/paper1.pdf',
                                    fileType: 'pdf',
                                    size: 2048576
                                },
                                {
                                    name: '实验数据.xlsx',
                                    url: 'https://example.com/data1.xlsx',
                                    fileType: 'xlsx',
                                    size: 512000
                                }
                            ])
                        },
                        {
                            id: 2,
                            title: '智能家居控制系统发明专利',
                            achievementType: 2,
                            level: 2,
                            course: '物联网技术',
                            semester: '2024-2025-1',
                            status: 1,
                            teacherId: 2,
                            teacherName: 'zhangzihan',
                            createTime: '2024-10-10 09:15:00',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '专利申请书.pdf',
                                    url: 'https://example.com/patent1.pdf',
                                    fileType: 'pdf',
                                    size: 1024000
                                }
                            ])
                        },
                        {
                            id: 3,
                            title: '全国大学生数学建模竞赛一等奖',
                            achievementType: 3,
                            level: 1,
                            course: '数学建模',
                            semester: '2023-2024-2',
                            status: 2,
                            teacherId: 2,
                            teacherName: 'zhangzihan',
                            createTime: '2024-09-20 16:45:00',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '获奖证书.jpg',
                                    url: 'https://example.com/certificate1.jpg',
                                    fileType: 'jpg',
                                    size: 800000
                                },
                                {
                                    name: '参赛论文.pdf',
                                    url: 'https://example.com/competition_paper.pdf',
                                    fileType: 'pdf',
                                    size: 1500000
                                }
                            ])
                        },
                        {
                            id: 4,
                            title: '校园垃圾分类管理系统项目计划书',
                            achievementType: 4,
                            level: 4,
                            course: '软件工程',
                            semester: '2024-2025-1',
                            status: 0,
                            teacherId: 2,
                            teacherName: 'zhangzihan',
                            createTime: '2024-10-18 11:20:00',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '项目计划书.docx',
                                    url: 'https://example.com/project_plan.docx',
                                    fileType: 'docx',
                                    size: 1200000
                                }
                            ])
                        }
                    ],
                    total: 4
                }

                // 解析附件URL
                this.list = mockData.records.map(item => {
                    if (item.attachmentUrl) {
                        try {
                            item.attachments = JSON.parse(item.attachmentUrl)
                        } catch (e) {
                            item.attachments = []
                        }
                    } else {
                        item.attachments = []
                    }
                    return item
                })
                this.total = mockData.total
                this.listLoading = false
            }, 1000) */
        },
        handleFilter() {
            this.listQuery.pageNo = 1
            this.getList()
        },
        handleReset() {
            this.listQuery = {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                level: '',
                title: ''
            }
            this.getList()
        },
        handleAdd() {
            this.$router.push('/achievement/apply')
        },
        handleView(row) {
            this.$router.push(`/achievement/detail/${row.id}`)
        },
        handleEdit(row) {
            this.$router.push(`/achievement/apply?id=${row.id}`)
        },
        handleDelete(row) {
            this.$confirm(`确定要删除成果"${row.title}"吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteAchievement(row.id).then(() => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    this.getList()
                })
            })
        },
        handleDownloadAttachment(file) {
            window.open(file.url, '_blank')
        },
        canEdit(row) {
            // 只有待初审和初审拒绝的成果可以编辑
            return row.status === 0 || row.status === 2
        },
        canDelete(row) {
            // 只有待初审和初审拒绝的成果可以删除
            return row.status === 0 || row.status === 2
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '论文',
                2: '专利',
                3: '竞赛证书',
                4: '项目计划',
                5: '其他'
            }
            return typeMap[type] || '未知'
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                4: 'info',
                5: 'danger'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                0: '待初审',
                1: '初审通过',
                2: '初审拒绝',
                3: '终审通过',
                4: '终审拒绝'
            }
            return statusMap[status] || '未知'
        },
        getStatusTagType(status) {
            const statusMap = {
                0: 'info',
                1: 'warning',
                2: 'danger',
                3: 'success',
                4: 'danger'
            }
            return statusMap[status] || ''
        },
        getLevelLabel(level) {
            const levelMap = {
                1: '国家级',
                2: '省级',
                3: '市级',
                4: '校级'
            }
            return levelMap[level] || '未知'
        },
        getLevelTagType(level) {
            const levelMap = {
                1: 'danger',   // 国家级 - 红色
                2: 'warning',  // 省级 - 橙色
                3: 'primary',  // 市级 - 蓝色
                4: 'success'   // 校级 - 绿色
            }
            return levelMap[level] || 'info'
        },
        getFileIcon(fileType) {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'jpg': 'el-icon-picture',
                'jpeg': 'el-icon-picture',
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture'
            }
            return iconMap[fileType] || 'el-icon-document'
        }
    }
}
</script>

<style lang="scss" scoped>
.my-achievements-container {
    padding: 20px;
}

.filter-container {
    padding-bottom: 20px;
}

.title-text {
    cursor: pointer;
    color: #409EFF;

    &:hover {
        text-decoration: underline;
    }
}

.text-muted {
    color: #999;
}

.attachment-btn {
    padding: 0;
    font-size: 12px;
}

.attachment-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    cursor: pointer;

    &:hover {
        background-color: #f5f7fa;
    }
}

.file-icon {
    margin-right: 8px;
    color: #409EFF;
}

.file-name {
    font-size: 12px;
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>